#pragma once

#include "BaseDefine.h"
#include "MathEngine.h"
namespace WorldWind
{
	/// <summary>
	/// Bounding sphere.  The tightest sphere that will fit the bounded object, 
	/// that is, the smallest radius sphere that all points lie within. 
	/// </summary>
	public class BoundingSphere
	{
		public D3DXVECTOR3 Center;
		public float Radius;

		/// <summary>
		/// Initializes a new instance of the <see cref= "T:WorldWind.BoundingSphere"/> class
		/// from a center point and a radius.
		/// </summary>
		public BoundingSphere(D3DXVECTOR3 center, float radius)
		{
			this.Center = center;
			this.Radius = radius;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref= "T:WorldWind.BoundingSphere"/> class
		/// from a set of lat/lon values (degrees)
		/// </summary>
		public BoundingSphere( float south, float north, float west, float east, float radius1, float radius2)
		{
			// Compute the points in world coordinates
			const int CornerCount = 8;
			D3DXVECTOR3 corners[CornerCount];

			float scale = radius2 / radius1;
			corners[0] = MathEngine.SphericalToCartesian(south, west, radius1);
			D3DXVec3Scale(&corners[1],corners[0], scale);
			corners[2] = MathEngine.SphericalToCartesian(south, east, radius1);
			D3DXVec3Scale(&corners[3],corners[2], scale);
			corners[4] = MathEngine.SphericalToCartesian(north, west, radius1);
			D3DXVec3Scale(&corners[5],corners[4], scale);
			corners[6] = MathEngine.SphericalToCartesian(north, east, radius1);
			D3DXVec3Scale(&corners[7],corners[6], scale);

			//Find the center.  In this case, we'll simply average the coordinates. 
			for (int i=0;i<CornerCount;i++)
			{
				Center += corners[i];
			}
			D3DXVec3Scale(&Center,&Center,(float)(1.0/CornerCount));

			//Loop through the coordinates and find the maximum distance from the center.  This is the radius.		
			D3DXVECTOR3 temp;
			for (int i=0;i<CornerCount;i++)
			{
				D3DXVec3Subtract(&temp,&corners[i],&Center);
				float distSq = D3DXVec3LengthSq(temp);
				if (distSq > Radius)
					Radius = distSq;
			}

			Radius = (float)sqrt(Radius);			
		}		
	}
}
